import os
import sys
import subprocess
import platform
import shutil

def create_venv():
    """创建并激活虚拟环境"""
    venv_dir = os.path.join(os.path.dirname(__file__), ".venv")
    
    # 检查虚拟环境是否存在
    if not os.path.exists(venv_dir):
        print("正在创建虚拟环境...")
        subprocess.check_call([sys.executable, "-m", "venv", venv_dir])
    
    # 获取激活脚本路径
    if platform.system() == "Windows":
        activate_script = os.path.join(venv_dir, "Scripts", "activate.bat")
        pip_path = os.path.join(venv_dir, "Scripts", "pip.exe")
    else:
        activate_script = os.path.join(venv_dir, "bin", "activate")
        pip_path = os.path.join(venv_dir, "bin", "pip")
    
    # 检查激活脚本是否存在
    if not os.path.exists(activate_script):
        print(f"无法找到激活脚本: {activate_script}")
        print("虚拟环境可能创建失败，请手动创建并激活虚拟环境。")
        return False
        
    return venv_dir, pip_path

def install_dependencies(pip_path):
    """安装所有依赖"""
    req_file = os.path.join(os.path.dirname(__file__), "requirements.txt")
    
    if os.path.exists(req_file):
        print("正在安装所有依赖...")
        try:
            # 先升级pip
            subprocess.check_call([pip_path, "install", "--upgrade", "pip"])
            
            # 确保安装cryptography
            subprocess.check_call([pip_path, "install", "cryptography==41.0.5"])
            
            # 安装所有依赖
            subprocess.check_call([pip_path, "install", "-r", req_file])
            
            # 额外确保flask-cors安装
            subprocess.check_call([pip_path, "install", "flask-cors==4.0.0"])
            
            print("所有依赖安装完成！")
            return True
        except subprocess.CalledProcessError as e:
            print(f"安装依赖时出错: {e}")
            return False
    else:
        print(f"找不到依赖文件: {req_file}")
        return False

def setup_env_file():
    """确保.env文件存在"""
    env_file = os.path.join(os.path.dirname(__file__), ".env")
    config_file = os.path.join(os.path.dirname(__file__), "config.env")
    
    if not os.path.exists(env_file) and os.path.exists(config_file):
        print("正在从config.env创建.env文件...")
        shutil.copy2(config_file, env_file)
        print(".env文件创建成功！")
    elif not os.path.exists(env_file):
        print("警告: 找不到.env或config.env文件。请手动创建配置文件。")

if __name__ == "__main__":
    print("="*60)
    print("多功能智能助手 - 环境设置")
    print("="*60)
    
    result = create_venv()
    if result:
        venv_dir, pip_path = result
        print(f"虚拟环境路径: {venv_dir}")
        
        if install_dependencies(pip_path):
            setup_env_file()
            print("\n环境设置完成！")
            
            # 显示激活命令
            if platform.system() == "Windows":
                print(f"\n要激活虚拟环境，请运行: .venv\\Scripts\\activate")
            else:
                print(f"\n要激活虚拟环境，请运行: source .venv/bin/activate")
        else:
            print("\n环境设置失败。")
    
    if platform.system() == "Windows":
        input("\n按 Enter 键退出...") 